package com.cuit.service.impl;

import com.cuit.entity.User;
import com.cuit.mapper.UserMapper;
import com.cuit.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    public PageInfo<User> getUsers(int page, int size, String keyword) {
        PageHelper.startPage(page, size);
        List<User> users = userMapper.selectByKeyword(keyword);
        return new PageInfo<>(users);
    }

    public void addUser(User user) {
        user.setCreateTime(LocalDateTime.now());
        userMapper.insert(user);
    }

    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }


    @Override
    public void updatePassword(Long userId, String newPassword) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 直接更新为明文新密码
        userMapper.updatePassword(userId, newPassword);
    }

    @Override
    public void updateUserInfo(User user) {
        // 直接更新用户信息（明文存储）
        userMapper.updateUser(user);
    }

    @Override
    public void updateAvatar(Long userId, String avatarUrl) {
        userMapper.updateAvatar(userId, avatarUrl);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }


}
